<template>
	<view class="container">
		<block v-if="isload">

			<dd-tab :itemdata="['一级(' + userinfo.myteamCount1 + ')', '二级(' + userinfo.myteamCount2 + ')']"
				:itemst="['1', '2', '3']" :st="st" :isfixed="false" @changetab="changetab"
				v-if="userlevel && userlevel.can_agent == 2"></dd-tab>
			<dd-tab
				:itemdata="['一级(' + userinfo.myteamCount1 + ')', '二级(' + userinfo.myteamCount2 + ')', '三级(' + userinfo.myteamCount3 + ')']"
				:itemst="['1', '2', '3']" :st="st" :isfixed="false" @changetab="changetab"
				v-if="userlevel && userlevel.can_agent == 3"></dd-tab>

			<view class="filter-section">
				<scroll-view scroll-x class="level-filter" :show-scrollbar="false">
					<view class="level-list">
						<view class="level-item" :class="{ active: selectedLevel === 'all' }"
							:style="selectedLevel === 'all' ? 'background:' + t('color1') + ';color:#fff' : 'background:#f5f5f5;color:#666'"
							@tap="selectLevel('all')">
							<text>全部({{ datalist.length }})</text>
						</view>
						<view class="level-item" v-for="level in levelList" :key="level.id"
							:class="{ active: selectedLevel === level.id }"
							:style="selectedLevel === level.id ? 'background:' + t('color1') + ';color:#fff' : 'background:#f5f5f5;color:#666'"
							@tap="selectLevel(level.id)">
							<text>{{ level.name }}({{ level.count }})</text>
						</view>
					</view>
				</scroll-view>
			</view>

			<view class="topsearch flex-y-center">
				<view class="f1 flex-y-center">
					<image class="img" src="/static/img/search_ico.png"></image>
					<input :value="keyword" placeholder="输入昵称/姓名/手机号搜索"
						placeholder-style="font-size:24rpx;color:#C2C2C2" @confirm="searchConfirm"
						@input="searchChange"></input>
				</view>
			</view>

			<view class="content" v-if="datalist && datalist.length > 0">
				<view class="label">
					<text class="t1">成员信息</text>
					<!-- 来自TA的 -->
					<text class="t2">{{ t('佣金') }}</text>
					<text class="t2" v-if="userinfo.levelid == 2">{{ t('毛利润') }}</text>
				</view>
				<view class="ci2" v-for="(item, index) in filteredTeamList" :key="index">
					<view class="it1">
						<view class="item">
							<view class="f1">
								<image :src="item.headimg"></image>
								<view class="t2">
									<text class="x1">{{ item.nickname }}</text>
									<text class="x2">{{ item.createtime }}</text>
									<text class="x2">等级：{{ item.levelname }}</text>
									<text class="x2" v-if="item.tel">手机号：{{ item.tel }}</text>
								</view>
							</view>

							<view class="f2">
								<text class="t1">+{{ item.commission }}</text>
								<!-- <text class='t2'>{{item.downcount}}个成员</text> -->
								<view class="t3">

								</view>
							</view>

							<view class="f2" v-if="userinfo.levelid == 2">
								<text class="t1">+{{ item.grossprofit }}</text>
							</view>

						</view>

					</view>
					<view class="it2">
						<view class="it2item">
							<view v-if="userlevel && userlevel.team_givemoney == 1" class="x1" @tap="givemoneyshow"
								:data-id="item.id">转{{ t('佣金') }}</view>
							<view v-if="userlevel && userlevel.team_givescore == 1" class="x1" @tap="givescoreshow"
								:data-id="item.id">转{{ t('积分') }}</view>
							<view v-if="userlevel && userlevel.team_levelup == 1" class="x1" @tap="showDialog"
								:data-id="item.id" :data-levelid="item.levelid" :data-levelsort="item.levelsort">升级
							</view>
						</view>
					</view>

				</view>
			</view>
			<uni-popup id="dialogmoneyInput" ref="dialogmoneyInput" type="dialog">
				<uni-popup-dialog mode="input" title="转账金额" value="" placeholder="请输入转账金额"
					@confirm="givemoney"></uni-popup-dialog>
			</uni-popup>
			<uni-popup id="dialogscoreInput" ref="dialogscoreInput" type="dialog">
				<uni-popup-dialog mode="input" title="转账数量" value="" placeholder="请输入转账数量"
					@confirm="givescore"></uni-popup-dialog>
			</uni-popup>

			<view v-if="dialogShow" class="popup__container">
				<view class="popup__overlay" @tap.stop="showDialog"></view>
				<view class="popup__modal">
					<view class="popup__title">
						<text class="popup__title-text">升级</text>
						<image src="/static/img/close.png" class="popup__close" style="width:36rpx;height:36rpx"
							@tap.stop="showDialog" />
					</view>
					<view class="popup__content">
						<view class="sheet-item" v-for="(item, index) in levelList" :key="index">
							<text class="item-text flex-item">{{ item.name }}</text>
							<view class="flex1"></view>
							<view @tap="changeLevel" :data-id="item.id" :data-name="item.name"
								v-if="item.id != tempLevelid && item.sort > tempLevelsort"
								:style="{ 'color': t('color1') }">选择</view>
							<view v-else style="color: #ccc;">选择</view>
						</view>
					</view>
				</view>
			</view>
		</block>
		<nodata v-if="nodata"></nodata>
		<nomore v-if="nomore"></nomore>
		<loading v-if="loading"></loading>
		<dp-tabbar :opt="opt"></dp-tabbar>
		<popmsg ref="popmsg"></popmsg>
	</view>
</template>

<script>
var app = getApp();

export default {
	data() {
		return {
			opt: {},
			loading: false,
			isload: false,
			menuindex: -1,

			st: 1,
			datalist: [],
			pagenum: 1,
			userlevel: {},
			userinfo: {},
			textset: {},
			keyword: '',
			tomid: '',
			tomoney: 0,
			toscore: 0,
			nodata: false,
			nomore: false,
			dialogShow: false,
			tempMid: '',
			tempLevelid: '',
			tempLevelsort: '',
			selectedLevel: 'all',
		};
	},

	onLoad: function (opt) {
		this.opt = app.getopts(opt);
		this.getdata();
	},
	onPullDownRefresh: function () {
		this.getdata();
	},
	onReachBottom: function () {
		if (!this.nodata && !this.nomore) {
			this.pagenum = this.pagenum + 1
			this.getdata(true);
		}
	},
	computed: {
		levelList() {
			if (!this.datalist || this.datalist.length === 0) return []

			// 先统计每个等级的人数
			const levelCounts = this.datalist.reduce((acc, item) => {
				if (item.levelid && item.levelname) {
					const key = `${item.levelid}-${item.levelname}`
					acc[key] = (acc[key] || 0) + 1
				}
				return acc
			}, {})

			// 转换成数组并去重
			const uniqueLevels = new Set()
			this.datalist.forEach(item => {
				if (item.levelid && item.levelname) {
					const key = `${item.levelid}-${item.levelname}`
					uniqueLevels.add(JSON.stringify({
						id: item.levelid,
						name: item.levelname,
						count: levelCounts[key] || 0
					}))
				}
			})

			return Array.from(uniqueLevels)
				.map(item => JSON.parse(item))
				.sort((a, b) => a.id - b.id)
		},
		filteredTeamList() {
			if (this.selectedLevel === 'all') {
				return this.datalist
			}
			return this.datalist.filter(item => item.levelid === this.selectedLevel)
		}
	},
	methods: {
		getdata: function (loadmore) {
			if (!loadmore) {
				this.pagenum = 1;
				this.datalist = [];
			}
			var that = this;
			var st = that.st;
			var pagenum = that.pagenum;
			var keyword = that.keyword;
			that.loading = true;
			that.nodata = false;
			that.nomore = false;
			app.post('Agent/team', {
				st: st,
				pagenum: pagenum,
				keyword: keyword
			}, function (res) {
				that.loading = false;
				var data = res.datalist;
				if (pagenum == 1) {
					that.userinfo = res.userinfo;
					that.userlevel = res.userlevel;
					that.textset = app.globalData.textset;
					that.datalist = data;
					if (data.length == 0) {
						that.nodata = true;
					}
					uni.setNavigationBarTitle({
						title: that.t('我的团队')
					});
					that.loaded();
				} else {
					if (data.length == 0) {
						that.nomore = true;
					} else {
						var datalist = that.datalist;
						var newdata = datalist.concat(data);
						that.datalist = newdata;
					}
				}
			});
		},
		changetab: function (st) {
			this.st = st;
			uni.pageScrollTo({
				scrollTop: 0,
				duration: 0
			});
			this.getdata();
		},
		givemoneyshow: function (e) {
			var that = this;
			var id = e.currentTarget.dataset.id;
			that.tomid = id;
			that.$refs.dialogmoneyInput.open();
		},
		givescoreshow: function (e) {
			var that = this;
			var id = e.currentTarget.dataset.id;
			that.tomid = id;
			that.$refs.dialogscoreInput.open();
		},
		givemoney: function (done, money) {
			var that = this;
			var id = that.tomid;
			app.showLoading('提交中');
			app.post('Agent/givemoney', {
				id: id,
				money: money
			}, function (res) {
				app.showLoading(false);
				if (res.status == 0) {
					app.error(res.msg);
				} else {
					app.success(res.msg);
					that.getdata();
					that.$refs.dialogmoneyInput.close();
				}
			})
		},
		givescore: function (done, score) {
			var that = this;
			var id = that.tomid;
			app.showLoading('提交中');
			app.post('Agent/givescore', {
				id: id,
				score: score
			}, function (res) {
				app.showLoading(false);
				if (res.status == 0) {
					app.error(res.msg);
				} else {
					app.success(res.msg);
					that.getdata();
					that.$refs.dialogscoreInput.close();
				}
			})
		},
		searchChange: function (e) {
			this.keyword = e.detail.value;
		},
		searchConfirm: function (e) {
			var that = this;
			var keyword = e.detail.value;
			that.keyword = keyword;
			that.getdata();
		},
		showDialog: function (e) {
			let that = this;
			that.tempMid = e.currentTarget.dataset.id;
			that.tempLevelid = e.currentTarget.dataset.levelid;
			that.tempLevelsort = e.currentTarget.dataset.levelsort;
			this.dialogShow = !this.dialogShow
		},
		changeLevel: function (e) {
			var that = this;
			var mid = that.tempMid;
			var levelId = e.currentTarget.dataset.id;
			var levelName = e.currentTarget.dataset.name;
			app.confirm('确定要升级为' + levelName + '吗?', function () {
				app.showLoading('提交中');
				app.post('Agent/levelUp', {
					mid: mid,
					levelId: levelId
				}, function (res) {
					app.showLoading(false);
					if (res.status == 0) {
						app.error(res.msg);
					} else {
						app.success(res.msg);
						that.dialogShow = false;
						that.getdata();
					}
				});
			});
		},
		selectLevel(levelId) {
			this.selectedLevel = levelId
		},
	}
};
</script>
<style>
.topsearch {
	width: 94%;
	margin: 16rpx 3%;
}

.topsearch .f1 {
	height: 60rpx;
	border-radius: 30rpx;
	border: 0;
	background-color: #fff;
	flex: 1
}

.topsearch .f1 .img {
	width: 24rpx;
	height: 24rpx;
	margin-left: 10px
}

.topsearch .f1 input {
	height: 100%;
	flex: 1;
	padding: 0 20rpx;
	font-size: 28rpx;
	color: #333;
}

.content {
	width: 94%;
	margin: 0 3%;
	border-radius: 16rpx;
	/* background: #fff; */
	margin-top: 20rpx;
}

.content .label {
	display: flex;
	width: 100%;
	padding: 16rpx;
	color: #333;
}

.content .label .t1 {
	flex: 1
}

.content .label .t2 {
	width: 200rpx;
	text-align: right
}

.ci2 {
	border-radius: 30rpx;
	margin-bottom: 35rpx;
	background-color: #fff;
}

.content .item {
	width: 100%;
	padding: 32rpx;
	border-top: 1px #eaeaea solid;
	min-height: 112rpx;
	display: flex;
	align-items: center;
}

.content .item image {
	max-width: 90rpx;
	max-height: 90rpx;
	border-radius: 4px
}

.content .item .f1 {
	display: flex;
	flex: 1;
	align-items: center;
}

.content .item .f1 .t2 {
	display: flex;
	flex-direction: column;
	padding-left: 20rpx
}

.content .item .f1 .t2 .x1 {
	color: #333;
	font-size: 26rpx;
}

.content .item .f1 .t2 .x2 {
	color: #999;
	font-size: 24rpx;
}

.content .item .f2 {
	display: flex;
	flex-direction: column;
	width: 200rpx;
	text-align: right;
	border-left: 1px solid #eee
}

.content .item .f2 .t1 {
	font-size: 40rpx;
	color: #666;
	height: 40rpx;
	line-height: 40rpx;
}

.content .item .f2 .t2 {
	font-size: 28rpx;
	color: #999;
	height: 50rpx;
	line-height: 50rpx;
}

.content .item .f2 .t3 {
	display: flex;
	justify-content: space-around;
	margin-top: 10rpx;
	flex-wrap: wrap;
}

.content .item .f2 .t3 .x1 {
	height: 40rpx;
	line-height: 40rpx;
	padding: 0 16rpx;
	border: 1px solid #ccc;
	border-radius: 6rpx;
	font-size: 22rpx;
	color: #666;
	margin-top: 10rpx;
}

.it1 {
	border-bottom: 1px #eaeaea solid;
}

.it2 {
	width: 100%;
}

.it2item {
	display: flex;
	flex-direction: row;
	justify-content: flex-end;
	padding: 20rpx;
	gap: 40rpx;

}

.it2item .x1 {
	height: 50rpx;
	line-height: 50rpx;
	padding: 0 18rpx;

	border-radius: 10rpx;
	font-size: 24rpx;
	/* 		border: 1px solid #ccc;
		color: #666; */
	color: #fff;
	background: #ba1f25;
}

.sheet-item {
	display: flex;
	align-items: center;
	padding: 20rpx 30rpx;
}

.sheet-item .item-img {
	width: 44rpx;
	height: 44rpx;
}

.sheet-item .item-text {
	display: block;
	color: #333;
	height: 100%;
	padding: 20rpx;
	font-size: 32rpx;
	position: relative;
	width: 90%;
}

.sheet-item .item-text:after {
	position: absolute;
	content: '';
	height: 1rpx;
	width: 100%;
	bottom: 0;
	left: 0;
	border-bottom: 1rpx solid #eee;
}

.man-btn {
	line-height: 100rpx;
	text-align: center;
	background: #FFFFFF;
	font-size: 30rpx;
	color: #FF4015;
}

.filter-section {
	background: #fff;
	padding: 20rpx 0;
	border-bottom: 1rpx solid #f5f5f5;
}

.level-filter {
	width: 100%;
	white-space: nowrap;
}

.level-list {
	display: inline-flex;
	padding: 0 20rpx;
}

.level-item {
	padding: 10rpx 20rpx;
	margin-right: 20rpx;
	border-radius: 26rpx;
	font-size: 26rpx;
	color: #666;
	background: #f5f5f5;
	transition: all 0.3s;
}

.level-item.active {
	color: #fff;
	background: #ba1f25;
}

.level-item:last-child {
	margin-right: 0;
}
</style>